import React, { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Tabs, Popup, Toast, Dialog } from 'antd-mobile';
import axios from 'axios';
import { getSchoolId, getUserInfo, getUsername, getUserId } from '../utils/auth';
import GestureRecognizerComponent from '../may/mediapipe_test';
import { http, host, port } from '../utils/host'
// 定义用户信息接口
interface UserInfo {
  userId: string;
  username: string;
  avatar?: string;
  // 其他用户相关字段
}

// 定义动态信息接口
interface Dongtai {
  _id: string;
  userId: string;
  username: string;
  content: string;
  images?: string[];
  video?: string;
  likeCount: number;
  commentCount: number;
  shareCount: number;
  publishTime: string;
  // 其他动态相关字段
}

// 定义话题接口
interface Topic {
  _id: string;
  title: string;
  // 其他话题相关字段
}

const Caochang: React.FC = () => {
  const navigate = useNavigate();

  // 表白墙导航函数
  const handleNavigateToConfession = (): void => {
    navigate('/confession-wall');
  };
  // 悬浮按钮位置状态
  const [fabPosition, setFabPosition] = useState<{ x: number; y: number }>({
    x: window.innerWidth - 75,
    y: window.innerHeight - 130
  });
  const handleNavigateToPublish = (): void => {
    navigate('/publish');
  };
  const [isDragging, setIsDragging] = useState<boolean>(false);
  // 分享功能状态
  const [showSharePopup, setShowSharePopup] = useState<boolean>(false);
  const [currentDongtaiId, setCurrentDongtaiId] = useState<string>('');
  // 评论功能状态
  const [showCommentDialog, setShowCommentDialog] = useState<boolean>(false);
  const [commentContent, setCommentContent] = useState<string>('');
  // 点赞状态
  const [likedDongtais, setLikedDongtais] = useState<Record<string, boolean>>({});
  // 当前用户信息
  const [currentUser, setCurrentUser] = useState<UserInfo | null>(null);
  // 添加激活的标签状态
  const [activeTab, setActiveTab] = useState<'follow' | 'school'>('follow');
  const dragStartPos = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
  const fabRef = useRef<HTMLDivElement | null>(null);

  // 处理拖动开始事件
  const handleDragStart = (e: React.MouseEvent<HTMLDivElement> | React.TouchEvent<HTMLDivElement>): void => {
    e.preventDefault();
    const clientX = e.type === 'mousedown' ? (e as React.MouseEvent<HTMLDivElement>).clientX : (e as React.TouchEvent<HTMLDivElement>).touches[0].clientX;
    const clientY = e.type === 'mousedown' ? (e as React.MouseEvent<HTMLDivElement>).clientY : (e as React.TouchEvent<HTMLDivElement>).touches[0].clientY;

    dragStartPos.current = {
      x: clientX - fabPosition.x,
      y: clientY - fabPosition.y
    };
    setIsDragging(true);
  };

  // 处理拖动过程事件
  const handleDrag = (e: MouseEvent | TouchEvent): void => {
    if (!isDragging) return;

    const clientX = e.type === 'mousemove' ? (e as MouseEvent).clientX : (e as TouchEvent).touches[0].clientX;
    const clientY = e.type === 'mousemove' ? (e as MouseEvent).clientY : (e as TouchEvent).touches[0].clientY;

    const newX = clientX - dragStartPos.current.x;
    const newY = clientY - dragStartPos.current.y;

    // 限制拖动范围在屏幕内，确保不超过底部标签栏
    const bottomNavHeight = 100; // 假设底部导航栏高度为100px
    const maxX = window.innerWidth - 70;
    const maxY = window.innerHeight - bottomNavHeight - 20; // 确保在底部标签栏上方

    setFabPosition({
      x: Math.max(10, Math.min(newX, maxX)),
      y: Math.max(10, Math.min(newY, maxY))
    });
  };

  // 处理拖动结束事件
  const handleDragEnd = (): void => {
    setIsDragging(false);
  };

  // 添加和移除事件监听器
  useEffect(() => {
    if (isDragging) {
      document.addEventListener('mousemove', handleDrag);
      document.addEventListener('mouseup', handleDragEnd);
      document.addEventListener('touchmove', handleDrag);
      document.addEventListener('touchend', handleDragEnd);
    } else {
      document.removeEventListener('mousemove', handleDrag);
      document.removeEventListener('mouseup', handleDragEnd);
      document.removeEventListener('touchmove', handleDrag);
      document.removeEventListener('touchend', handleDragEnd);
    }

    return () => {
      document.removeEventListener('mousemove', handleDrag);
      document.removeEventListener('mouseup', handleDragEnd);
      document.removeEventListener('touchmove', handleDrag);
      document.removeEventListener('touchend', handleDragEnd);
    };
  }, [isDragging]);

  // 热门话题数据
  const [topics, setTopics] = useState<Topic[]>([]);
  // 话题ID到话题标题的映射
  const [topicMap, setTopicMap] = useState<Record<string, string>>({});

  // 动态数据
  const [dongtaiList, setDongtaiList] = useState<Dongtai[]>([]);
  const [followingDongtaiList, setFollowingDongtaiList] = useState<Dongtai[]>([]);
  const [loading, setLoading] = useState(false);
  const [followingLoading, setFollowingLoading] = useState(false);

  // 获取关注用户列表
  const fetchFollowingUsers = async (): Promise<UserInfo[]> => {
    if (!currentUser) return [];

    try {
      const response = await axios.get(`${http}${host}${port}/users/following?userId=${currentUser.userId}`);
      return response.data.following || [];
    } catch (error) {
      console.error('获取关注用户列表失败:', error);
      return [];
    }
  };

  // 获取关注用户的动态
  const fetchFollowingDongtai = async (): Promise<void> => {
    setFollowingLoading(true);
    try {
      console.log('当前用户ID:', currentUser?.userId);
      if (!currentUser?.userId) {
        console.error('用户未登录，无法获取关注动态');
        setFollowingDongtaiList([]);
        return;
      }

      const response = await axios.get<Dongtai[]>(
        `${http}${host}${port}/dongtai/getFollowingDongtai?userId=${currentUser.userId}`
      );
      console.log('关注动态接口响应状态:', response.status);
      console.log('获取到的关注动态数量:', response.data.length);
      setFollowingDongtaiList(response.data);
    } catch (error) {
      console.error('获取关注用户动态失败:', error);
      setFollowingDongtaiList([]);
    } finally {
      setFollowingLoading(false);
    }
  };

  // 打开分享弹窗
  const openSharePopup = (dongtaiId: string): void => {
    setCurrentDongtaiId(dongtaiId);
    setShowSharePopup(true);
  };

  // 关闭分享弹窗
  const closeSharePopup = (): void => {
    setShowSharePopup(false);
  };

  // 执行分享操作
  const handleShare = async (type: 'wechat' | 'weibo' | 'copy' | 'more'): Promise<void> => {
    try {
      // 更新分享计数
      const response = await axios.post<{ shareCount: number }>(`${http}${host}${port}/dongtai/share`, {
        dongtaiId: currentDongtaiId
      });

      // 更新动态列表中的分享数量
      setDongtaiList(prevList => {
        return prevList.map(item => {
          if (item._id === currentDongtaiId) {
            return {
              ...item,
              shareCount: response.data.shareCount
            };
          }
          return item;
        });
      });

      // 生成分享链接
      const shareUrl = `${http}${host}${port}/dongtai/${currentDongtaiId}`;
      const shareTitle = '分享一条动态';

      // 根据分享类型执行不同操作
      switch (type) {
        case 'wechat':
          // 微信分享 - 这里使用微信开放标签或URL Scheme
          // 注意：实际项目中需要引入微信SDK并配置appid
          if (window.wx) {
            wx.showMenuItems({
              menuList: ['menuItem:share:appMessage'], // 分享给朋友
            });
            wx.onMenuShareAppMessage({
              title: shareTitle,
              link: shareUrl,
              imgUrl: `${http}${host}${port}/logo.png`, // 替换为实际图片
              success: function () {
                Toast.show({ content: '微信分享成功', type: 'success', position: 'center' });
              },
              cancel: function () {
                Toast.show({ content: '取消微信分享', type: 'none', position: 'center' });
              }
            });
          } else {
            // 没有微信SDK时，提供复制链接方案
            await navigator.clipboard.writeText(shareUrl);
            Toast.show({ content: '链接已复制，请在微信中粘贴分享', type: 'success', position: 'center' });
          }
          break;
        case 'weibo':
          // 微博分享
          const weiboShareUrl = `http://service.weibo.com/share/share.php?url=${encodeURIComponent(shareUrl)}&title=${encodeURIComponent(shareTitle)}`;
          window.open(weiboShareUrl, '_blank');
          Toast.show({ content: '正在跳转到微博', type: 'success', position: 'center' });
          break;
        case 'copy':
          // 复制链接到剪贴板
          await navigator.clipboard.writeText(shareUrl);
          Toast.show({ content: '分享链接已复制到剪贴板', type: 'success', position: 'center' });
          break;
        case 'more':
          // 更多分享选项
          if (navigator.share) {
            navigator.share({
              title: shareTitle,
              url: shareUrl
            }).then(() => {
              Toast.show({ content: '分享成功', type: 'success', position: 'center' });
            }).catch((err) => {
              console.error('分享失败:', err);
              Toast.show({ content: '分享失败', type: 'fail', position: 'center' });
            });
          } else {
            await navigator.clipboard.writeText(shareUrl);
            Toast.show({ content: '链接已复制，请手动分享', type: 'success', position: 'center' });
          }
          break;
        default:
          await navigator.clipboard.writeText(shareUrl);
          Toast.show({ content: '分享链接已复制到剪贴板', type: 'success', position: 'center' });
      }

      closeSharePopup();
    } catch (error) {
      console.error('分享操作失败:', error);
      Toast.show({ content: '分享失败，请重试', type: 'fail', position: 'center' });
    }
  };

  // 获取动态数据
  const fetchDongtai = async (): Promise<void> => {
    const schoolId = getSchoolId();
    if (!schoolId) {
      console.error('未获取到学校ID');
      return;
    }

    setLoading(true);
    try {
      const response = await axios.get<Dongtai[]>(`${http}${host}${port}/dongtai/getDongtai?schoolId=${schoolId}`);
      setDongtaiList(response.data);
    } catch (error) {
      console.error('获取动态失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取当前用户信息
  useEffect(() => {
    const user = getUserInfo() || null;
    setCurrentUser(user);
    console.log('用户信息已加载:', user?.userId);
  }, []);

  // 在组件加载、标签切换或用户信息变化时获取相应动态
  useEffect(() => {
    console.log('触发动态获取 useEffect: 标签=', activeTab, '用户=', currentUser?.userId);
    if (activeTab === 'school') {
      fetchDongtai();
    } else if (activeTab === 'follow') {
      if (currentUser && currentUser.userId) {
        fetchFollowingDongtai();
      } else {
        console.log('用户未登录，不获取关注动态');
        setFollowingLoading(false);
        setFollowingDongtaiList([]);
        // 只有当用户明确切换到关注标签页时才显示提示

      }
    }
  }, [activeTab, currentUser]);

  // 处理点赞/取消点赞
  const handleLike = async (dongtaiId) => {
    if (!currentUser) {
      Toast.show({ content: '请先登录', type: 'fail', position: 'center' });
      return;
    }

    try {
      const isLiked = likedDongtais[dongtaiId] || false;
      const response = await axios.post(`${http}${host}${port}/dongtai/like`, {
        dongtaiId,
        like: !isLiked
      });

      // 更新点赞状态
      setLikedDongtais(prev => ({
        ...prev,
        [dongtaiId]: !isLiked
      }));

      // 根据当前激活的标签页更新对应的动态列表
      if (activeTab === 'school') {
        setDongtaiList(prevList => {
          return prevList.map(item => {
            if (item._id === dongtaiId) {
              return {
                ...item,
                likeCount: response.data.likeCount
              };
            }
            return item;
          });
        });
      } else if (activeTab === 'follow') {
        setFollowingDongtaiList(prevList => {
          return prevList.map(item => {
            if (item._id === dongtaiId) {
              return {
                ...item,
                likeCount: response.data.likeCount
              };
            }
            return item;
          });
        });
      }

      Toast.show({ content: isLiked ? '已取消点赞' : '点赞成功', type: 'success', position: 'center' });
    } catch (error) {
      console.error('点赞操作失败:', error);
      Toast.show({ content: '操作失败，请重试', type: 'fail', position: 'center' });
    }
  };

  // 打开评论对话框
  const openCommentDialog = (dongtaiId) => {
    setCurrentDongtaiId(dongtaiId);
    setCommentContent('');
    setShowCommentDialog(true);
  };

  // 关闭评论对话框
  const closeCommentDialog = () => {
    setShowCommentDialog(false);
  };

  // 提交评论
  const submitComment = async () => {
    if (!commentContent.trim()) {
      Toast.show({ content: '评论内容不能为空', type: 'fail', position: 'center' });
      return;
    }

    if (!currentUser) {
      Toast.show({ content: '请先登录', type: 'fail', position: 'center' });
      return;
    }

    try {
      const response = await axios.post(`${http}${host}${port}/dongtai/comment`, {
        dongtaiId: currentDongtaiId,
        content: commentContent,
        userId: currentUser._id,
        username: currentUser.username
      });

      // 更新动态列表中的评论数量
      setDongtaiList(prevList => {
        return prevList.map(item => {
          if (item._id === currentDongtaiId) {
            return {
              ...item,
              commentCount: response.data.commentCount
            };
          }
          return item;
        });
      });

      closeCommentDialog();
      Toast.show({ content: '评论成功', type: 'success', position: 'center' });
    } catch (error) {
      console.error('评论操作失败:', error);
      Toast.show({ content: '评论失败，请重试', type: 'fail', position: 'center' });
    }
  };

  useEffect(() => {
    const fetchTopics = async () => {
      try {
        const response = await axios.get(`${http}${host}${port}/hua/detail`);
        setTopics(response.data.slice(0, 6)); // 仍然只显示前6个热门话题

        // 构建话题ID到标题的映射（使用所有话题）
        const map = {};
        response.data.forEach(topic => {
          map[topic._id] = topic.title;
        });
        setTopicMap(map);
      } catch (error) {
        console.error('Failed to fetch hot topics:', error);
      }
    };

    fetchTopics();
  }, []);
  // 格式化时间差
  const formatTimeDifference = (createdAt) => {
    if (!createdAt) return '';
    const now = new Date();
    const past = new Date(createdAt);
    const difference = now - past;

    const seconds = Math.floor(difference / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);
    const months = Math.floor(days / 30);
    const years = Math.floor(months / 12);

    if (years > 0) return `${years}年前`;
    if (months > 0) return `${months}个月前`;
    if (days > 0) return `${days}天前`;
    if (hours > 0) return `${hours}小时前`;
    if (minutes > 0) return `${minutes}分钟前`;
    return '刚刚';
  };

  return (
    <div style={styles.container}>
      {/* 页面标题 */}
      <h1 style={styles.title}>操场</h1>

      {/* 热门话题区域 */}
      <div style={styles.hotTopicsSection}>
        <div style={styles.sectionHeader}>
          <span style={styles.sectionTitle}>热门话题</span>
          <span style={styles.moreLink} onClick={() => navigate('/topic-square')}>全部</span>
        </div>
        <div style={styles.topicsGrid}>
          {topics.map(topic => (
            <div key={topic._id} style={styles.topicItem} onClick={() => navigate(`/topic-detail/${topic._id}`)}>{topic.title}</div>
          ))}
          <div style={styles.topicItem} onClick={handleNavigateToConfession}>表白墙</div>
        </div>
      </div>

      {/* 关注区域 */}
      <div style={styles.followingSection}>
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          style={styles.tabs}
        >
          <Tabs.Tab title="关注" key="follow" />
          <Tabs.Tab title="本校" key="school" />
        </Tabs>

      </div>

      {activeTab === 'follow' ? (
        followingLoading ? (
          <div style={styles.loadingState}>
            <div style={styles.spinner}></div>
            <p style={styles.loadingText}>加载中...</p>
          </div>
        ) : followingDongtaiList.length > 0 ? (
          <div style={styles.dongtaiList}>
            {followingDongtaiList.map((item) => (
              <div key={item._id} style={styles.dongtaiItem}>
                <div style={styles.userInfo}>
                  <img
                    src={item.avatarImage || 'default-avatar.png'}
                    alt=""
                    style={styles.avatar}
                    onClick={() => navigate(`/user-detail/${item.userId}`)}
                    onError={(e) => {
                      // 如果本地存储的头像加载失败，回退到默认头像
                      (e.target as HTMLImageElement).src = "";
                    }}
                  />
                  <div style={styles.userInfoText}>
                    <div style={styles.userName} onClick={() => navigate(`/user-detail/${item.userId}`)}>{item.username || getUsername() || item.userId}</div>
                    <div style={styles.publishTime}>{formatTimeDifference(item.createdAt)}</div>
                  </div>
                </div>
                <div style={styles.content}>{item.title}</div>
                {item.media && item.media.length > 0 && (
                  <div style={styles.mediaContainer}>
                    {item.media.map((url, index) => {
                      // 检查文件扩展名以确定媒体类型
                      const isVideo = url.match(/\.(mp4|mov|webm|avi|mkv)$/i);
                      const mediaUrl = `${http}${host}${port}` + url;

                      if (isVideo) {
                        return (
                          <video
                            key={index}
                            src={mediaUrl}
                            alt=""
                            style={styles.mediaVideo}
                            controls
                            loop
                            muted
                            playsInline
                          />
                        );
                      } else {
                        return (
                          <img
                            key={index}
                            src={mediaUrl}
                            alt=""
                            style={styles.mediaImage}
                          />
                        );
                      }
                    })}
                  </div>
                )}
                {/* 话题展示 */}
                {item.huaId && topicMap[item.huaId] && (
                  <div style={styles.topicTag} onClick={() => navigate(`/topic-detail/${item.huaId}`)}>
                    # {topicMap[item.huaId]}
                  </div>
                )}

                <div style={styles.interactionBar}>
                  <span
                    style={{ ...styles.interactionIcon, cursor: 'pointer', color: likedDongtais[item._id] ? '#FF6B6B' : '#333' }}
                    onClick={() => handleLike(item._id)}
                  >
                    👍 {item.likeCount}
                  </span>
                  <span style={{ ...styles.interactionIcon, cursor: 'pointer' }} onClick={() => navigate(`/dongtai-detail/${item._id}`)}>💬 {item.commentCount}</span>
                  <span style={{ ...styles.interactionIcon, cursor: 'pointer' }} onClick={() => openSharePopup(item._id)}>🔄 {item.shareCount}</span>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div style={styles.emptyState}>
            <div style={styles.illustration}>
              {/* SVG 插图 - 关注页面 */}
              <svg width="100%" height="100%" viewBox="0 0 200 200" fill="none" xmlns="http://www.w3.org/2000/svg">
                <rect x="60" y="100" width="80" height="60" rx="5" fill="#F5F5F5" />
                <rect x="80" y="120" width="40" height="5" rx="2.5" fill="#FF9F43" />
                <circle cx="85" cy="85" r="15" fill="#FFD166" />
                <circle cx="115" cy="70" r="20" fill="#FF9F43" />
                <path d="M130 100C130 130 150 140 150 140" stroke="#FF9F43" strokeWidth="4" strokeLinecap="round" />
                <path d="M110 160L110 130" stroke="#333" strokeWidth="2" />
                <path d="M90 160L90 130" stroke="#333" strokeWidth="2" />
                <circle cx="140" cy="50" r="10" fill="#FF9F43" />
              </svg>
            </div>
            <p style={styles.emptyText}>暂无关注任何同学</p>
          </div>
        )
      ) : (
        loading ? (
          <div style={styles.loadingState}>
            <div style={styles.spinner}></div>
            <p style={styles.loadingText}>加载中...</p>
          </div>
        ) : dongtaiList.length > 0 ? (
          <div style={styles.dongtaiList}>
            {dongtaiList.map((item) => (
              <div key={item._id} style={styles.dongtaiItem}>
                <div style={styles.userInfo}>
                  <img
                    src={item.avatarImage || 'default-avatar.png'}
                    alt=""
                    style={styles.avatar}
                    onClick={() => navigate(`/user-detail/${item.userId}`)}
                    onError={(e) => {
                      // 如果本地存储的头像加载失败，回退到默认头像
                      (e.target as HTMLImageElement).src = "";
                    }}
                  />
                  <div style={styles.userInfoText}>
                    <div style={styles.userName} onClick={() => navigate(`/user-detail/${item.userId}`)}>{item.username || getUsername() || item.userId}</div>
                    <div style={styles.publishTime}>{formatTimeDifference(item.createdAt)}</div>
                  </div>
                </div>
                <div style={styles.content}>{item.title}</div>
                {item.media && item.media.length > 0 && (
                  <div style={styles.mediaContainer}>
                    {item.media.map((url, index) => {
                      // 检查文件扩展名以确定媒体类型
                      const isVideo = url.match(/\.(mp4|mov|webm|avi|mkv)$/i);
                      const mediaUrl = `${http}${host}${port}` + url;

                      if (isVideo) {
                        return (
                          <video
                            key={index}
                            src={mediaUrl}
                            alt=""
                            style={styles.mediaVideo}
                            controls
                            loop
                            muted
                            playsInline
                          />
                        );
                      } else {
                        return (
                          <img
                            key={index}
                            src={mediaUrl}
                            alt=""
                            style={styles.mediaImage}
                          />
                        );
                      }
                    })}
                  </div>
                )}
                {/* 话题展示 */}
                {item.huaId && topicMap[item.huaId] && (
                  <div style={styles.topicTag}>
                    # {topicMap[item.huaId]}
                  </div>
                )}

                <div style={styles.interactionBar}>
                  <span
                    style={{ ...styles.interactionIcon, cursor: 'pointer', color: likedDongtais[item._id] ? '#FF6B6B' : '#333' }}
                    onClick={() => handleLike(item._id)}
                  >
                    👍 {item.likeCount}
                  </span>
                  <span style={{ ...styles.interactionIcon, cursor: 'pointer' }} onClick={() => navigate(`/dongtai-detail/${item._id}`)}>💬 {item.commentCount}</span>
                  <span style={{ ...styles.interactionIcon, cursor: 'pointer' }} onClick={() => openSharePopup(item._id)}>🔄 {item.shareCount}</span>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div style={styles.emptyState}>
            <div style={styles.illustration}>
              {/* SVG 插图 - 本校页面 */}
              <svg width="100%" height="100%" viewBox="0 0 200 200" fill="none" xmlns="http://www.w3.org/2000/svg">
                <rect x="50" y="90" width="100" height="70" rx="5" fill="#F0F0F0" />
                <rect x="70" y="110" width="60" height="6" rx="3" fill="#6C63FF" />
                <rect x="70" y="125" width="40" height="6" rx="3" fill="#6C63FF" />
                <circle cx="100" cy="60" r="25" fill="#6C63FF" opacity="0.7" />
                <path d="M60 170L60 140" stroke="#333" strokeWidth="2" />
                <path d="M140 170L140 140" stroke="#333" strokeWidth="2" />
              </svg>
            </div>
            <p style={styles.emptyText}>暂无本校动态</p>
          </div>
        )
      )}



      <div
        ref={fabRef}
        style={{
          ...styles.fab,
          left: fabPosition.x + 'px',
          top: fabPosition.y + 'px',
          right: 'auto',
          bottom: 'auto',
          cursor: isDragging ? 'grabbing' : 'grab'
        }}
        onMouseDown={handleDragStart}
        onTouchStart={handleDragStart}
        onClick={handleNavigateToPublish}
      >
        <span style={styles.fabText}>+</span>
      </div>

      {/* 分享功能Popup */}
      <Popup
        visible={showSharePopup}
        onClose={closeSharePopup}
        position="bottom"
        bodyStyle={{ height: 'auto', padding: '24px 0 16px' }}
        closeOnMaskClick={true}
      >
        <div style={styles.sharePopupHeader}>
          <h3 style={styles.shareTitle}>立即分享给好友</h3>
        </div>
        <div style={styles.shareOptions}>
          <div style={styles.shareOption} onClick={() => handleShare('wechat')}>
            <div style={styles.shareIcon}>🟢</div>
            <div style={styles.shareText}>微信</div>
          </div>
          <div style={styles.shareOption} onClick={() => handleShare('weibo')}>
            <div style={styles.shareIcon}>🔴</div>
            <div style={styles.shareText}>微博</div>
          </div>
          <div style={styles.shareOption} onClick={() => handleShare('copy')}>
            <div style={styles.shareIcon}>🔗</div>
            <div style={styles.shareText}>复制链接</div>
          </div>
          <div style={styles.shareOption} onClick={() => handleShare('more')}>
            <div style={styles.shareIcon}>📤</div>
            <div style={styles.shareText}>分享</div>
          </div>
        </div>
        <div style={styles.shareCancel} onClick={closeSharePopup}>
          <span style={styles.cancelText}>取消</span>
        </div>
      </Popup>

      {/* 评论对话框 */}
      <Dialog
        visible={showCommentDialog}
        onClose={closeCommentDialog}
        title="发表评论"
        confirmText="发送"
        onConfirm={submitComment}
        cancelText="取消"
        onCancel={closeCommentDialog}
      >
        <div style={{ padding: '10px 0' }}>
          <textarea
            style={{ width: '100%', padding: '10px', border: '1px solid #ddd', borderRadius: '6px', fontSize: '14px', resize: 'none', boxSizing: 'border-box' }}
            placeholder="写下你的评论..."
            value={commentContent}
            onChange={(e) => setCommentContent(e.target.value)}
            rows={4}
          />
        </div>
      </Dialog>
    </div>
  );
};

// 添加CSS动画
const styleSheet = document.createElement('style');
styleSheet.textContent = `
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
`;
document.head.appendChild(styleSheet);

// 格式化时间差函数
const formatTimeDifference = (publishTime) => {
  if (!publishTime) return '';

  const now = new Date();
  const publishDate = new Date(publishTime);
  const diffInSeconds = Math.floor((now - publishDate) / 1000);

  // 计算不同时间单位的差值
  const secondsInMinute = 60;
  const secondsInHour = secondsInMinute * 60;
  const secondsInDay = secondsInHour * 24;
  const secondsInMonth = secondsInDay * 30;
  const secondsInYear = secondsInDay * 365;

  if (diffInSeconds < secondsInMinute) {
    return `${diffInSeconds}秒前`;
  } else if (diffInSeconds < secondsInHour) {
    return `${Math.floor(diffInSeconds / secondsInMinute)}分钟前`;
  } else if (diffInSeconds < secondsInDay) {
    return `${Math.floor(diffInSeconds / secondsInHour)}小时前`;
  } else if (diffInSeconds < secondsInMonth) {
    return `${Math.floor(diffInSeconds / secondsInDay)}天前`;
  } else if (diffInSeconds < secondsInYear) {
    return `${Math.floor(diffInSeconds / secondsInMonth)}个月前`;
  } else {
    return `${Math.floor(diffInSeconds / secondsInYear)}年前`;
  }
};

// 移动端优化样式
const styles = {
  container: {
    width: '100%',
    maxWidth: '100%',
    padding: '16px 0',
    fontFamily: 'Arial, sans-serif',
    backgroundColor: '#FFFFFF',
    minHeight: '100vh',
    overflowX: 'hidden',
    boxSizing: 'border-box',
    position: 'relative',
    margin: '0 auto'
  },
  title: {
    fontSize: '22px',
    fontWeight: 'bold',
    marginBottom: '20px',
    color: '#333',
    paddingLeft: '16px',
  },
  hotTopicsSection: {
    marginBottom: '24px',
    paddingLeft: '16px',
    paddingRight: '16px',
  },
  sectionHeader: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: '12px',
    padding: '0 8px',
  },
  sectionTitle: {
    fontSize: '16px',
    fontWeight: 'bold',
    color: '#FF6B6B',
  },
  moreLink: {
    fontSize: '14px',
    color: '#999',
  },
  topicsGrid: {
    display: 'grid',
    gridTemplateColumns: '1fr 1fr',
    gap: '10px',
    padding: '0 4px',
  },
  topicItem: {
    padding: '12px 10px',
    backgroundColor: '#F8F9FA',
    borderRadius: '8px',
    fontSize: '14px',
    color: '#333',
    boxShadow: '0 1px 2px rgba(0,0,0,0.05)',
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    maxWidth: '100%',
  },
  illustration: {
    marginBottom: '20px',
    width: '100%',
    maxWidth: '180px',
    height: 'auto',
  },
  followingSection: {
    backgroundColor: '#FFF',
    borderRadius: '12px',
    boxShadow: '0 2px 10px rgba(0,0,0,0.05)',
    overflow: 'hidden',
    marginLeft: '16px',
    marginRight: '16px',
  },
  tabs: {
    '--title-font-size': '15px',
    '--active-line-color': '#FF6B6B',
    '--active-title-color': '#333',
    '--title-color': '#999',
    '--content-padding': '0px',
  },
  emptyState: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    padding: '40px 20px',
    minHeight: '300px',
  },

  emptyText: {
    fontSize: '15px',
    color: '#999',
    textAlign: 'center',
  },
  loadingState: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    padding: '40px 20px',
    minHeight: '300px',
  },
  spinner: {
    width: '40px',
    height: '40px',
    border: '4px solid #f3f3f3',
    borderTop: '4px solid #FF6B6B',
    borderRadius: '50%',
    animation: 'spin 1s linear infinite',
    marginBottom: '20px',
  },
  loadingText: {
    fontSize: '15px',
    color: '#999',
  },
  dongtaiList: {
    padding: '10px',
  },
  dongtaiItem: {
    backgroundColor: '#fff',
    borderRadius: '12px',
    padding: '16px',
    marginBottom: '16px',
    boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
  },
  userInfo: {
    display: 'flex',
    alignItems: 'center',
    marginBottom: '10px',
  },
  avatar: {
    width: '36px',
    height: '36px',
    borderRadius: '50%',
    backgroundColor: '#f0f0f0',
    marginRight: '10px',
  },
  userName: {
    fontSize: '14px',
    fontWeight: 'bold',
    color: '#333',
    marginBottom: '2px',
  },
  userInfoText: {
    display: 'flex',
    flexDirection: 'column',
  },
  publishTime: {
    fontSize: '12px',
    color: '#999',
  },
  content: {
    fontSize: '15px',
    color: '#333',
    marginBottom: '10px',
  },
  mediaContainer: {
    display: 'flex',
    flexWrap: 'wrap',
    gap: '8px',
    marginBottom: '10px',
  },
  mediaImage: {
    width: '100%',
    height: 'auto',
    borderRadius: '8px',
    maxHeight: '200px',
    objectFit: 'cover',
  },
  mediaVideo: {
    width: '100%',
    height: 'auto',
    borderRadius: '8px',
    maxHeight: '200px',
    objectFit: 'cover',
    backgroundColor: '#000',
  },
  topicTag: {
    display: 'inline-block',
    padding: '4px 8px',
    backgroundColor: '#FFF0F0',
    color: '#FF6B6B',
    fontSize: '12px',
    borderRadius: '4px',
    marginBottom: '10px',
    cursor: 'pointer',
  },
  interactionBar: {
    display: 'flex',
    justifyContent: 'space-between',
    paddingTop: '10px',
    borderTop: '1px solid #f0f0f0',
  },
  interactionIcon: {
    fontSize: '14px',
    color: '#999',
  },
  fab: {
    position: 'fixed',
    width: '56px',
    height: '56px',
    borderRadius: '50%',
    backgroundColor: '#FF6B6B',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    boxShadow: '0 4px 12px rgba(255,107,107,0.4)',
    zIndex: 100,
    touchAction: 'none',
    userSelect: 'none',
  },
  fabText: {
    fontSize: '24px',
    color: 'white',
    fontWeight: 'bold',
  },
  // 分享弹窗样式
  sharePopupHeader: {
    textAlign: 'center',
    marginBottom: '20px',
  },
  shareTitle: {
    fontSize: '16px',
    fontWeight: 'bold',
    color: '#333',
    margin: 0,
  },
  shareOptions: {
    display: 'flex',
    justifyContent: 'space-around',
    padding: '0 20px',
    marginBottom: '30px',
  },
  shareOption: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    cursor: 'pointer',
  },
  shareIcon: {
    width: '50px',
    height: '50px',
    borderRadius: '50%',
    backgroundColor: '#F8F9FA',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    fontSize: '24px',
    marginBottom: '8px',
  },
  shareText: {
    fontSize: '12px',
    color: '#666',
  },
  shareCancel: {
    textAlign: 'center',
    padding: '12px 0',
    borderTop: '1px solid #F0F0F0',
    cursor: 'pointer',
  },
  cancelText: {
    fontSize: '16px',
    color: '#FF6B6B',
    fontWeight: 'bold',
  },
};

export default Caochang;